package edu.whu.assignment7.service.impl;

import edu.whu.assignment7.entity.User;
import edu.whu.assignment7.exception.SelfException;
import edu.whu.assignment7.mapper.UserMapper;
import edu.whu.assignment7.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int registration(String username, String password) throws SelfException{
        //检查是否有同名用户
        User same = userMapper.selectByUsername(username);
        if(same != null) {
            throw new SelfException("已经有同名用户存在，请更换用户名");
        }
        //存储用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int result = userMapper.insert(user);
        return result;
    }

    @Override
    public int login(String username, String password) throws SelfException{
        //检查用户是否存在
        User same = userMapper.selectByUsername(username);
        if(same == null) {
            throw new SelfException("用户名不存在");
        }
        //检查用户密码是否相同
        if(!password.equals(same.getPassword())) {
            throw new SelfException("密码错误，请重新输入");
        }
        else {
            return 1;
        }
    }
}
